package com.xiaohe.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xiaohe.common.to.mq.SeckillOrderTo;
import com.xiaohe.common.utils.R;
import com.xiaohe.common.vo.MemberResponseVo;
import com.xiaohe.gulimall.seckill.feign.CouponFeignService;
import com.xiaohe.gulimall.seckill.feign.ProductFeignService;
import com.xiaohe.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.xiaohe.gulimall.seckill.service.SeckillService;
import com.xiaohe.gulimall.seckill.to.SecKillSkuRedisTO;
import com.xiaohe.gulimall.seckill.vo.SecKillSessionWithSkus;
import com.xiaohe.gulimall.seckill.vo.SeckillSkuVo;
import com.xiaohe.gulimall.seckill.vo.SkuInfoVo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    private  final String SESSIONS_CACHE_PREFIX="seckill:sessions:";
    private  final String SKUKILL_CACHE_PREFIX="seckill:skus:";

    private final String SKU_STOCK_SEMAPHORE ="seckill:stock:";//+商品随机码



    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void uploadSexKillSkuLatest3Days() {
        //1、去扫描要参加秒杀的
        R late3DaySession = couponFeignService.getLate3DaySession();
        if (late3DaySession.getCode() == 0){
            //上架商品
            List<SecKillSessionWithSkus> sessionData = (List<SecKillSessionWithSkus>) late3DaySession.getData(new TypeReference<List<SecKillSessionWithSkus>>() {
            });
            //缓存到redis中
            //1、缓存活动信息
            saveSessionInfos(sessionData);
            //2、缓存活动关联的商品信息
            saveSessionSkuInfo(sessionData);
        }
    }

    @Override
    public List<SecKillSkuRedisTO> getCurrentSeckillSkus() {
        //确定当前时间属于哪个秒杀场次
        long time = new Date().getTime();
        Set<String> keys = redisTemplate.keys("SESSIONS_CACHE_PREFIX" + "*");
        for (String key : keys) {
            String replace = key.replace("seckill:sessions:", "");
            String[] s = replace.split("_");
            Long start =Long.parseLong(s[0]);
            Long end =Long.parseLong(s[1]);
            //当前所用的场次信息
            if(time>=start && time<=end){
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> list = hashOps.multiGet(range);
                if(list!=null){
                    List<SecKillSkuRedisTO> collect = list.stream().map(item -> {
                        SecKillSkuRedisTO redis = JSON.parseObject(item.toString(), SecKillSkuRedisTO.class);
//                        redis.setRandomCode(null);
                        return redis;
                    }).collect(Collectors.toList());
                    return collect;
                }


                break;
            }
        }
        //获取这个秒杀场次需要的所有商品信息

        return null;
    }

    @Override
    public SecKillSkuRedisTO skuSkuSeckillInfo(Long skuId) {
        //找到所有参与秒杀的商品key信息
        BoundHashOperations<String, String, String> operations = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = operations.keys();
        if(keys!=null&& keys.size()>0){
            String reg ="\\d_"+skuId;
            for (String key : keys) {
                boolean matches = Pattern.matches(reg, key);
                if(matches){
                    String json = operations.get(key);
                    SecKillSkuRedisTO secKillSkuRedisTO = JSON.parseObject(json, SecKillSkuRedisTO.class);
                    //随机码，只要上当前时间才返回
                    Long startTime = secKillSkuRedisTO.getStartTime();
                    long current = new Date().getTime();
                    if(current>=startTime&& current<=secKillSkuRedisTO.getEndTime()){
                    }else {
                        secKillSkuRedisTO.setRandomCode(null);
                    }
                    return secKillSkuRedisTO;
                }
            }
        }

        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {

        MemberResponseVo loginUser = LoginUserInterceptor.getLoginUser();
        //1、合法性校验
        //1.1、获取秒杀商品的详细信息
        BoundHashOperations<String, String, String> operations = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String s = operations.get(killId);
        if (StringUtils.isEmpty(s)){
            return null;
        }else {
            SecKillSkuRedisTO secKillSkuRedisTO = JSON.parseObject(s, SecKillSkuRedisTO.class);
            //校验合法性
            //1.2校验秒杀时间
            Long startTime = secKillSkuRedisTO.getStartTime();
            Long endTime = secKillSkuRedisTO.getEndTime();
            long time = new Date().getTime();
            if(time>=startTime && time<=endTime){
                //1.3、随机码校验和商品id是否正确
                String randomCode = secKillSkuRedisTO.getRandomCode();
                String skuId = secKillSkuRedisTO.getPromotionSessionId()+"_"+secKillSkuRedisTO.getSkuId();
                if (randomCode.equals(key) && killId.equals(skuId)){
                   //是否购买过了
                    String redisKey =loginUser.getId()+"_"+skuId;
                    //自动过期
                    long ttl = endTime-time;
                    Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                    if (aBoolean){
                        //占位成功说明这个人没有买过
                        //分布式信号量
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            boolean b = semaphore.tryAcquire(num);
                        if(b){
                            //秒杀成功
                            //快速下单，发送MQ消息
                            String timeId = IdWorker.getTimeId();
                            SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                            seckillOrderTo.setOrderSn(timeId);
                            seckillOrderTo.setMemberId(loginUser.getId());
                            seckillOrderTo.setNum(num);
                            seckillOrderTo.setPromotionSessionId(secKillSkuRedisTO.getPromotionSessionId());
                            seckillOrderTo.setSkuId(secKillSkuRedisTO.getSkuId());
                            seckillOrderTo.setSeckillPrice(secKillSkuRedisTO.getSeckillPrice());
                            rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",seckillOrderTo);
                            return timeId;
                            }
                        //已经买过
                        return null;
                    }

                }else {
                    return null;
                }
            }else {
                return null;
            }
        }
        return null;
    }

    private void saveSessionInfos(List<SecKillSessionWithSkus>  secKillSessionWithSkus){
        secKillSessionWithSkus.stream().forEach(session->{
            Long startTime = session.getStartTime().getTime();
            Long endTime = session.getEndTime().getTime();
            String key =SESSIONS_CACHE_PREFIX+startTime+"_"+endTime;
            //缓存活动信息
            Boolean aBoolean = redisTemplate.hasKey(key);
            if(!aBoolean){
                List<String> collect = session.getRelationSkus().stream().map(item->item.getPromotionSessionId().toString()+"_"+item.getSkuId().toString()).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key,collect);
            }
        });

    }

    private void saveSessionSkuInfo(List<SecKillSessionWithSkus> secKillSessionWithSkus){

        secKillSessionWithSkus.stream().forEach(session->{
            //准备Hash操作
            BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            List<SeckillSkuVo> relationSkus = session.getRelationSkus();
            relationSkus.stream().forEach(seckillSkuVo -> {
                String uuid = UUID.randomUUID().toString().replace("-", "");
                Boolean aBoolean1 = operations.hasKey(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString());
                if(!aBoolean1){
                    //缓存商品
                    SecKillSkuRedisTO secKillSkuRedisTO = new SecKillSkuRedisTO();
                    //1、sku的基本数据
                    R skuinfo = productFeignService.getSkuinfo(seckillSkuVo.getSkuId());
                    if (skuinfo.getCode() == 0){
                        SkuInfoVo skuInfo = (SkuInfoVo) skuinfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        secKillSkuRedisTO.setSkuInfoVo(skuInfo);
                    }
                    //2、sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo,secKillSkuRedisTO);
                    //3、设置秒杀时间
                    secKillSkuRedisTO.setStartTime(session.getStartTime().getTime());
                    secKillSkuRedisTO.setEndTime(session.getEndTime().getTime());
                    //4、设置商品的随机码

                    secKillSkuRedisTO.setRandomCode(uuid);

                    String jsonString = JSON.toJSONString(secKillSkuRedisTO);
                    operations.put(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString(),jsonString);
                    //如果当前这个场次的商品的信息已经上架
                    //引入分布式信号量，限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + uuid);
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                }
            });
        });
    }
}
